<template>
  <div class="search-container">
    <h1>搜索交易记录</h1>
    <van-button
      square
      style="background: #51915d; color: white; border-radius: 8px;"
      @click="queryEvents"
      :loading="isRolling"
      class="dice-btn"
      title="点击查询事件日志"
    >
      {{ isRolling ? "查询事件日志中..." : "📦查询事件日志" }}
    </van-button>
    <br>
    <div class="search-results">
      <ul>
        <br>
        <br>
        <li v-for="event in events" :key="event.blockNumber">
          <p><strong>区块号:</strong> {{ event.blockNumber }}</p>
          <p><strong>玩家:</strong> {{ shortenAddress(event.returnValues.player) }}</p>
          <p><strong>投掷结果:</strong> {{ event.returnValues.diceResult }}</p>
          <p><strong>新位置:</strong> {{ event.returnValues.newPosition }}</p>
          <p><strong>事件消息:</strong> {{ event.returnValues.eventMessage }}</p>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import { contractInstance } from '../util'; // 导入 web3 和 contractInstance

export default {
  name: 'SearchTransactions',
  data() {
    return {
      events: [], // 用于存储查询到的事件日志
      isRolling: false, // 用于控制按钮加载状态
    };
  },
  methods: {
    // 地址格式化方法
    shortenAddress(address) {
      if (!address) return 'N/A';
      const start = address.slice(0, 6); // 前6位
      const end = address.slice(-4); // 后4位
      return `${start}...${end}`; // 格式化后的地址
    },
    async queryEvents() {
      this.isRolling = true; // 开始加载
      if (window.ethereum) {
        try {
          // 请求用户解锁 MetaMask
          await window.ethereum.request({ method: 'eth_requestAccounts' });

          // 获取用户的账户地址
          const accounts = await window.ethereum.request({ method: 'eth_accounts' });
          const account = accounts[0];

          // 查询事件日志
          const events = await contractInstance.getPastEvents('DiceRolled', {
            fromBlock: 'earliest',
            toBlock: 'latest',
            filter: { player: account },
          });

          // 存储查询到的事件日志
          this.events = events;
        } catch (error) {
          console.error('查询事件失败:', error);
        } finally {
          this.isRolling = false; // 加载完成
        }
      } else {
        console.log('请安装 MetaMask 插件');
        this.isRolling = false; // 确保加载状态结束
      }
    },
  },
};
</script>

<style>
.search-container {
  margin: 20px;
  padding: 20px;
  border: 1px solid #cccccc6c;
  border-radius: 5px;
  background-color: #f9f9f940;
  font-family: 'Arial', sans-serif; /* 设置默认字体 */
}

.search-results ul {
  list-style-type: none;
  padding: 0;
}

.search-results li {
  margin-bottom: 10px;
  padding: 10px;
  background-color: #f9f9f997;
  border: 1px solid #ddd;
  border-radius: 3px;
}
</style>
